package cn.navclub.xt.server

import cn.navclub.xt.server.api.CommonResult
import cn.navclub.xt.server.codgen.RestRespCodegen
import cn.navclub.xt.server.config.DATABASE
import cn.navclub.xt.server.util.DBUtil
import io.vertx.core.DeploymentOptions
import io.vertx.core.Vertx
import io.vertx.kotlin.coroutines.await
import kotlinx.coroutines.runBlocking
import java.io.File
import java.lang.Exception

val units = listOf(
    "kt:cn.navclub.xt.server.gateway.TCPVerticel",
    "kt:cn.navclub.xt.server.gateway.WebVerticel",
    "kt:cn.navclub.xt.server.gateway.UDPVerticle",
    "kt:cn.navclub.xt.server.verticle.OBSVerticel",
    "kt:cn.navclub.xt.server.verticle.SSOVerticel"
)

fun main(): Unit = runBlocking {
    val vertx = Vertx.vertx()
    try {

        //初始化配置信息
        val fs = vertx.fileSystem()
        val buf = fs.readFile("config/config.json").await()
        val json = buf.toJsonObject()

        //初始化数据库连接
        DBUtil.init(vertx, json.getJsonObject(DATABASE)).await()

        //部署执行单元
        val options = DeploymentOptions().setConfig(json)
        for (unit in units) {
            vertx.deployVerticle(unit, options).await()
        }

        //注册数据解码器
        vertx.eventBus().registerDefaultCodec(CommonResult::class.java, RestRespCodegen())

    } catch (e: Exception) {
        e.printStackTrace()
        println("Vertx application startup fail cause:${e.message}")
        vertx.close().await()
    }
}